package com.tangcco.lockwell.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * json转List<String>
 *
 * @author yanxinping
 * @date 2025-01-02 11:23
 */
public class JsonArrayTypeHandler extends BaseTypeHandler<List<String>> {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        try {
            String jsonArrayString = objectMapper.writeValueAsString(parameter);
            ps.setString(i, jsonArrayString);
        } catch (Exception e) {
            throw new SQLException("Error converting List<String> to JSON string", e);
        }
    }
    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        try {
            String jsonArrayString = rs.getString(columnName);
            return objectMapper.readValue(jsonArrayString, ArrayList.class);
        } catch (Exception e) {
            throw new SQLException("Error converting JSON string to List<String>", e);
        }
    }
    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        try {
            String jsonArrayString = rs.getString(columnIndex);
            return objectMapper.readValue(jsonArrayString, ArrayList.class);
        } catch (Exception e) {
            throw new SQLException("Error converting JSON string to List<String>", e);
        }
    }
    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        try {
            String jsonArrayString = cs.getString(columnIndex);
            return objectMapper.readValue(jsonArrayString, ArrayList.class);
        } catch (Exception e) {
            throw new SQLException("Error converting JSON string to List<String>", e);
        }
    }

}

